<template>
  <div class="users">
<el-breadcrumb separator="/">
  <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- input框 -->
<el-input placeholder="请输入内容" v-model='searchVal'    class="input-with-select search-input" @keydown.enter.native="searchSous">
    <el-button slot="append" icon="el-icon-search" @click='searchSous'></el-button>
</el-input>
<!-- 点击的时候显示新增弹框 -->
    <el-button type="primary" plain @click="dialogFormVisible=true">添加用户</el-button>
    <!-- 表格 -->
 <el-table
 v-loading="loading"
    class="mt-15"
    :data="usersList"
    border
    style="width: 100%">
     <el-table-column
      type="index"
      width="50">
    </el-table-column>
    <el-table-column
      prop="username"
      label="名字"
      >
    </el-table-column>
    <el-table-column
      prop="email"
      label="邮箱"
      >
    </el-table-column>
    <el-table-column
      prop="mobile"
      label="电话"
      >
    </el-table-column>
    <el-table-column
      prop="mobile"
      label="状态"
      >
      <template slot-scope='scope'>
        <!-- 这里的v-model应该是scope.row.mg_state -->
      <el-switch
        v-model="scope.row.mg_state"
        @change="toggleState(scope.row)"
        active-color="#13ce66"
        inactive-color="#ff4949">
      </el-switch>
         </template>
    </el-table-column>
    <el-table-column
      prop="mobile"
      label="操作"
      >
      <!-- 操作按钮部分开始 -->
      <template slot-scope='scope'>
        <!-- 点击把所有的信息传递过去 -->
      <el-button type="primary" icon="el-icon-edit" circle @click="handleEditlUser(scope.row)"></el-button>
      <el-button type="success" icon="el-icon-check" circle @click="handleSelectUser(scope.row)"></el-button>
      <el-button type="danger" icon="el-icon-delete" circle @click="handleDelUser(scope.row.id)"></el-button>
      </template>
    </el-table-column>

  </el-table>

  <!-- 分页开始 -->
   <el-pagination
      class="mt-15"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="[10,20,30,40,50]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalNum">
    </el-pagination>

    <!-- 弹框开始 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules='formrules' ref='refForm'>
        <el-form-item label="名称" :label-width="formLabelWidth" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth"
        prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth"
        prop="mobile">
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
      </el-form>
  <div slot="footer" class="dialog-footer">
  <!-- 点击取消弹框隐藏 -->
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </div>
  </el-dialog>

  <!-- 编辑弹框 -->
      <el-dialog title="编辑用户" :visible.sync="EditdialogFormVisible">
      <el-form :model="Editform" :rules='Editformrules' ref='EditrefForm'>
        <el-form-item label="名称" :label-width="formLabelWidth" prop="username">
          <el-input v-model="Editform.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth"
        prop="email">
          <el-input v-model="Editform.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth"
        prop="mobile">
          <el-input v-model="Editform.mobile"></el-input>
        </el-form-item>
      </el-form>
  <div slot="footer" class="dialog-footer">
  <!-- 点击取消弹框隐藏 -->
    <el-button @click="EditdialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitEdit('EditrefForm')">确 定</el-button>
  </div>
  </el-dialog>
  <!-- 选择框开始 -->
  <el-dialog title="分配角色" :visible.sync="SelectdialogFormVisible">
  <el-form :model="Selectform">
    <el-form-item label="当前用户:" :label-width="SelectformLabelWidth">
      {{Selectform.username}}
    </el-form-item>
   <el-select v-model="roleId" placeholder="请选择">
    <el-option
      v-for="item in selectList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="SelectdialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click=select>确 定</el-button>
  </div>
</el-dialog>

  </div>
</template>

<script>
import {getUserList, getAddList, getDelList, getEditList, getAlterList, getTubeList, getAllocationList} from '@/api'
export default {
  data () {
    // 定义自定义校验规则所需的函数
    let checkEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入邮箱'))
      } else {
        // 校验邮箱规则
        // eslint-disable-next-line
        let emailReg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
        if (emailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }
    }

    // 定义自定义校验规则所需的函数
    let checkTel = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入电话号码'))
      } else {
        // 校验手机规则
        // eslint-disable-next-line
        let emailReg = /^1(3|4|5|7|8)\d{9}$/
        if (emailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的手机格式'))
        }
      }
    }
    return {
      searchVal: '', // 搜索框双向数据绑定
      currentPage4: 4,
      usersList: [],
      totalNum: 0, // 开始总条数为0
      pagesize: 10, // 每页显示多少条  默认为1条
      pagenum: 1, // 当前页码 默认为
      dialogFormVisible: false, // 一开始弹框隐藏
      form: {
        username: '',
        mobile: '',
        email: '',
        password: ''
      },
      formLabelWidth: '80px',
      SelectformLabelWidth: '80px',
      Selectform: {
        username: '',
        id: '' // 用户id
      },
      formrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: checkTel, trigger: 'blur' }
        ]
      },
      loading: true,
      EditdialogFormVisible: false,
      SelectdialogFormVisible: false,
      Editform: {
        id: -1,
        username: '',
        mobile: '',
        email: ''
      },
      Editformrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: checkTel, trigger: 'blur' }
        ]
      },
      // 选择框 角色
      selectList: [],
      roleId: '' // 角色id
    }
  },
  created () {
    this.initList()
  },
  methods: {
    // 查询
    initList () {
      getUserList({query: this.searchVal, pagenum: this.pagenum, pagesize: this.pagesize})
        .then(res => {
          this.usersList = res.data.users
          // 获取到总条数
          this.totalNum = res.data.total
          setTimeout(() => {
            this.loading = false
          }, 1000)
        })
    },
    // 添加
    addUser () {
      getAddList(this.form)
        .then(res => {
          // console.log(res)
          this.$message.success('添加用户成功')
          this.dialogFormVisible = false
          // 添加成功后清空表格数据
          this.username = ''
          this.mobile = ''
          this.email = ''
          this.password = ''
          // 添加成功刷新表格数据
          this.initList()
        })
    },
    // 分页
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val// 改变每页多少条的时候将值赋值给pagesize 接着再调用获取数据的方法
      this.initList()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.pagenum = val // 改变当前页码的时候将值赋值给pagenum 接着再调用获取数据的方法
      this.initList()
    },
    // 搜索
    searchSous () {
      this.initList()
      this.searchVal = ''
    },
    // 删除
    handleDelUser (id) {
      // alert(id)
      // 让提示框显示
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击确定执行的回调函数
        getDelList(id)
          .then(res => {
            if (res.meta.status === 200) {
              this.initList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message.error(res.meta.msg)
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 编辑
    handleEditlUser (row) {
      this.Editform.id = row.id
      this.Editform.username = row.username
      this.Editform.mobile = row.mobile
      this.Editform.email = row.email
      this.EditdialogFormVisible = true
    },
    submitEdit (ref) {
      this.$refs[ref].validate((isPass) => {
        if (isPass) {
          // js校验成功，则发送请求
          getEditList(this.Editform)
            .then(res => {
              // console.log(res)
              this.$message.success('编辑成功')
              this.EditdialogFormVisible = false
              this.initList()
            })
        } else {
          this.$message.warning('请正确填写表单')
        }
      })
    },
    // 切换状态
    toggleState (row) {
      getAlterList(row.id, row.mg_state)
        .then(res => {
          console.log(res)
          this.$message.success(res.meta.msg)
        })
    },
    // 选择框
    handleSelectUser (row) {
      // console.log(row)
      this.Selectform.username = row.username
      this.Selectform.id = row.id
      this.SelectdialogFormVisible = true
      this.roleId = row.role_name // 解决默认角色一样的bug
      getTubeList()
        .then(res => {
          // console.log(res)
          this.selectList = res.data
        })
    },
    // 角色分配
    select () {
      if (typeof this.roleId === 'string') {
        this.SelectdialogFormVisible = false
        return false
      }
      getAllocationList(this.Selectform.id, this.roleId)
        .then(res => {
          // console.log(res)
          this.$message.success(res.meta.msg)
          this.SelectdialogFormVisible = false
          this.initList()
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.users {
  .search-input {
    width: 300px;
  }
}
</style>
